<?php

namespace App\Service\User\remark;

use App\Cache\RedisKey;
use App\Cache\UserRemarkCache;
use App\Exception\ApiException;
use App\Helpers\RedisUtil;
use App\Model\UserRemark;
use App\Service\BaseService;

class RemarkSetService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
//        $userId = 35;
        $remark = $this->request->input('remark','');
        $toUserId = $this->request->input('to_user_id',0);

        if ($toUserId <= 0) throw new ApiException('用户ID错误');

        if ($toUserId == $userId) throw new ApiException('用户ID错误');

        $oldRemark = (new UserRemarkCache())->getRemark($userId, $toUserId);

        if ($oldRemark == $remark) {
            //备注未改变
            return ['msg' => '备注设置成功'];
        }

        $remarkModel = new UserRemark();
        $action = null;
        if ($oldRemark != '' && $remark == '') {
            //删除备注
            $action = $remarkModel->where('user_id', $userId)->where('to_user_id', $toUserId)->delete();
        }

        if ($remark != '' && $oldRemark == '') {
            //添加备注
            $action = $remarkModel->create([
                'user_id' => $userId,
                'to_user_id' => $toUserId,
                'remark' => $remark
            ]);
        }

        if ($remark != '' && $oldRemark != '' && $oldRemark != $remark) {
            //修改备注
            $action = $remarkModel->where('user_id', $userId)->where('to_user_id', $toUserId)->update(['remark' => $remark]);
        }

        if (empty($action))
        {
            throw new ApiException('备注设置失败');
        }

        $key = RedisKey::userRemarkList($userId);
        RedisUtil::getRedis()->del($key);

        return ['msg' => '备注设置成功'];
    }
}